package com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.impl;


import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.BeeSqlPrase;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.IBeeSqlPrase;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * foreach标签解析
 * @author Administrator
 *
 */
public class BeeSqlForEachPrase implements IBeeSqlPrase {
	
	/**
	 *  解析 foreach SQL语句
	 * @param sql
	 * @return
	 */
	 public  String praseSql(String sql,Map<String,Object> params) {
		 //	BaseDBService baseDBService = BeeSpringBean.getBean(BaseDBService.class);
		 	BeeSqlPrase prase = BeeSpringBean.getBean(BeeSqlPrase.class);
		    Pattern pattern = Pattern.compile(BeeCommonConstns.FOREACH_MATCH);
	        Matcher matcher = pattern.matcher(sql);
	        StringBuffer sb = new StringBuffer();
	        while (matcher.find()) {
	            String collection = matcher.group("collection");
	            String item = matcher.group("item");
	            //String index = matcher.group("index");
	            String open = matcher.group("open");
	            String close = matcher.group("close");
	            String separator = matcher.group("separator");
	            String content = matcher.group("content");
	            Object obj = params.get(collection);
	            StringBuilder csb = new StringBuilder(ObjectUtils.isEmpty(open)?"":open);
	            if(obj instanceof List) {
	            	List<Map<String,Object>> list = (List<Map<String,Object>>) obj;
	            	int num = 0;
	            	  for (Map<String,Object> element : list) {
	            		String str = content.replace(item, collection+"["+num+"]");
	            		str = str.trim().replaceAll("[\\r\\n]", "");
	            		//判断是否是赋值
	            		Pattern r = Pattern.compile(BeeCommonConstns.SET_PARAMS_MATH);
	            		Matcher m = r.matcher(sql);
	            		if(!m.find()) {	            		
	            			prase.paraseSql(str, params);
	            		}
	            		if(num < list.size()-1) {
	            			csb.append(str +separator);
	            		}else {
	            			csb.append(str);
	            		}
	  		            num++;
	  		        }
	            }
	            csb.append(ObjectUtils.isEmpty(close)?"":close);
	            matcher.appendReplacement(sb, csb.toString());
	        }
	        matcher.appendTail(sb);
	        return sb.toString();
	    }
}
